package org.jeecg.jt808.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.jeecg.jt808.modbus.MqttMessageJson;


import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import static org.jeecg.jt808.util.MD5.generateSignature;


public class JsonUtil {
    private static final Pattern JSON_PATTERN = Pattern.compile(
            "^\\s*(\\{.*}|\\[.*])\\s*$"
    );
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static boolean hasFields(String jsonString, String... fieldNames) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonString);

            for (String fieldName : fieldNames) {
                if (!jsonNode.has(fieldName)) {
                    return false;
                }
            }

            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public static String createMqttMessageJson(String data, String sn,String imei,String cmd,String seq ) throws  JsonProcessingException {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMddHHmmss");
        String currentTime =now.format(formatter);
        ObjectMapper objectMapper=new ObjectMapper();
        MqttMessageJson mqttMessageJson = new MqttMessageJson();
        mqttMessageJson.setId(sn);
        mqttMessageJson.setEnrc(0);
        mqttMessageJson.setVender(1);
        mqttMessageJson.setCmd(cmd);
        mqttMessageJson.setTimestamp(currentTime);
        mqttMessageJson.setSeq( seq );
        mqttMessageJson.setData(data);
        String sign=generateSignature(mqttMessageJson.getId(),mqttMessageJson.getEnrc(),mqttMessageJson.getVender(),mqttMessageJson.getCmd(),mqttMessageJson.getTimestamp(),mqttMessageJson.getSeq(),mqttMessageJson.getData());
        mqttMessageJson.setSign(sign);
        return objectMapper.writeValueAsString(mqttMessageJson);
    }
    public static boolean isJson(String jsonString) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            return true;
        } catch (Exception e) {
            return false;
        }
    }




    public static boolean is808Json(String jsonString) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            boolean hasIdAndCmd = hasFields(jsonString, "id", "cmd");
            if (!hasIdAndCmd){
                return false;
            }
            boolean hasIdAndData = hasFields(jsonString, "id", "data");
            if (!hasIdAndData){
                return  false;
            }

            boolean hasIdAndSeq = hasFields(jsonString, "id", "seq");
            if (!hasIdAndSeq){
                return  false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public static boolean isChargePileJson(String json) {
        try {
            JsonNode rootNode = objectMapper.readTree(json);
            // 检查必要字段
            if (rootNode.has("DEVICE") && rootNode.has("CMD")) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean isCabinetJson(String jsonString) {
        try {
            JsonNode jsonNode = objectMapper.readTree(jsonString);

            // 检查是否包含 "type" 和 "code" 字段
            if (!jsonNode.has("type") || !jsonNode.has("code")) {
                return false;
            }

            // 检查 "type" 字段的值是否为 "cmd"
            if (!"cmd".equals(jsonNode.get("type").asText())) {
                return false;
            }

            // 检查 "code" 字段的值是否为 "register", "heartbeat", "swap", "openDoor"
            String code = jsonNode.get("code").asText();
            return "register".equals(code) || "heartbeat".equals(code) || "swap".equals(code) || "openDoor".equals(code);
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isClientConnectJson(String jsonString) {
        try {
            JsonNode jsonNode = objectMapper.readTree(jsonString);

            // 检查是否包含 "username", "event", 和 "clientid" 字段
            if (!jsonNode.has("username") || !jsonNode.has("event") || !jsonNode.has("clientid")) {
                return false;
            }

            // 检查 "username" 和 "clientid" 字段是否为字符串类型
            if (!jsonNode.get("username").isTextual() || !jsonNode.get("clientid").isTextual()) {
                return false;
            }

            // 检查 "clientid" 是否为纯数字
            String clientId = jsonNode.get("clientid").asText();
            if (!clientId.matches("\\d+")) { // 使用正则表达式匹配纯数字
                return false;
            }

            return true;
        } catch (Exception e) {
            return false;
        }
    }







    public static String formatSeq(String seq) {
        if (seq.length() < 4) {
            return String.format("%04d", Integer.parseInt(seq));
        } else {
            return seq;
        }
    }

    public static float formatMileage(Float mileage) {
        if (mileage == null) {
            return 0f;
        }

        BigDecimal mileageBigDecimal = new BigDecimal(mileage).setScale(2, RoundingMode.HALF_UP);
        return mileageBigDecimal.floatValue();
    }
}
